package DAO.jpa;

import DAO.VagaDAO;
import Modelo.Vaga;

import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import util.JPAUtil;

public class VagaJpaDAO extends AbstractJpaDao<Vaga, Long> implements VagaDAO {

    public VagaJpaDAO() {
        super(Vaga.class);
    }

    @Override
    public List<Vaga> getAllActives() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Vaga> getAll() {
        return JPAUtil.getEntityManager().createQuery("from Vaga").getResultList();
    }

    public List<Vaga> getByFilters(Vaga vaga) {

        int filters = 0;

        List<Vaga> retorno = null;

        StringBuilder queryStr = new StringBuilder();

        queryStr.append("SELECT v FROM Vaga v WHERE ");

        if (!isBlank(vaga.getCodigo())) {
            queryStr.append(" v.codigo like :codigo ");
            filters++;
        }

        if (!isBlank(vaga.getCampus())) {

            if (filters > 0) {
                queryStr.append(" OR ");
            }

            queryStr.append(" v.campus like :campus ");
            filters++;
        }

        Query query = JPAUtil.getEntityManager().createQuery(queryStr.toString());

        if (!isBlank(vaga.getCodigo())) {
            query.setParameter("codigo", "%" + vaga.getCodigo() + "%");
        }

        if (!isBlank(vaga.getCampus())) {
            query.setParameter("campus", "%" + vaga.getCodigo() + "%");
        }

        retorno = query.getResultList();

        return retorno;
    }

    public Vaga getByPrimaryKey(Vaga vaga) throws NonUniqueResultException, NoResultException {

        Vaga retorno = null;

        StringBuilder queryStr = new StringBuilder();

        queryStr.append(" SELECT v FROM Vaga v WHERE id = :id ");

        Query query = JPAUtil.getEntityManager().createQuery(queryStr.toString());

        query.setParameter("id", vaga.getId());

        retorno = (Vaga) query.getSingleResult();

        return retorno;
    }

    public void insert(Vaga vaga) {

        JPAUtil.beginTransaction();

        persist(vaga);

        JPAUtil.commitTransaction();
    }

    private boolean isBlank(String str) {
        return (str == null) || (str.trim().equals(""));
    }
}